#pragma once 
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <strings.h>
#include <cstring>
#include <iostream>
#include <string>
#include "nocopy.hpp"

const static uint16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t port = defaultport)
        : _port(port)
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cerr << "创建套接字失败！" << std::endl;
            exit(0);
        }
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n != 0)
        {
            std::cerr << "绑定端口到文件失败！" << std::endl;
            exit(0);
        }
    }

    void start()
    {
        char buffer[defaultsize];
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer,
                &len);
            if(n > 0)
            {
                buffer[n] = 0;
                uint16_t port = ntohs(peer.sin_port);
                char ip[INET_ADDRSTRLEN];
                const char* ret = inet_ntop(AF_INET, &(peer.sin_addr), ip, INET_ADDRSTRLEN);
                if(ret == nullptr)
                {
                    std::cerr << "当前地址提取失败！" << std::endl;
                    exit(0);
                }
                std::cout << "[server say>" << ip << ":" << port << "]" << std::endl; 
            }
            n = sendto(_sockfd, buffer, strlen(buffer), 0, (sockaddr*)&peer, sizeof(peer));
            if(n == -1)
            {
                std::cerr << "发送消息给客户端错误！" << std::endl;
            }
        }
    }

    ~UdpServer(){}

    
private:
    uint16_t _port;
    int _sockfd;
};